package com.experiment.springboot_experiment3.controller;

import com.experiment.springboot_experiment3.pojo.RegionStats;
import com.experiment.springboot_experiment3.service.GetDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class GetDataController {

    @Autowired
    GetDataService getDataService;

    @GetMapping("/")
    public String index(Model model,String country){
        Integer latestTotalCases;
        Integer diffFromPrevDay;
        Date nowTime = new Date();
        List <RegionStats> totalList = getDataService.regionStatsList;
        if(country!=null){
            List <RegionStats> countList = totalList.stream().
                                            filter(regionStats -> regionStats.getCountry().equals(country))
                                            .collect(Collectors.toList());
            model.addAttribute("totalList",countList);
        }
        else {
            model.addAttribute("totalList",totalList);
        }
        latestTotalCases = totalList.stream().mapToInt(RegionStats::getLatestTotalCases).sum();
        diffFromPrevDay = totalList.stream().mapToInt(RegionStats::getDiffFromPrevDay).sum();

        model.addAttribute("latestTotalCases",latestTotalCases);
        model.addAttribute("diffFromPrevDay",diffFromPrevDay);
        model.addAttribute("nowTime",nowTime);
        System.out.println(country);
        return "index";
    }


}
